import base64
import random
from io import BytesIO
from captcha.image import ImageCaptcha
from django.http import HttpResponseForbidden, HttpResponse
from django.views import View
from django_redis import get_redis_connection


class ImageCodeView(View):
    def get(self, request):
        # 1.接收数据
        uuid = request.GET.get('uuid')
        # 2.校验数据
        if not uuid:
            return HttpResponseForbidden('uuid无效')
        # 3.处理业务
        # 生成图片文本内容和图片二进制代码
        text = ''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', k=4))
        image = ImageCaptcha()
        img_data = image.generate(text)
        img_base64 = base64.b64encode(img_data.read()).decode('utf-8')
        # data: image / png;
        # base64, {img_base64}
        # 4.把uuid和图片文本存入redis
        redis_client = get_redis_connection('img_code')  # 获取redis客户端
        # 5.写入redis(是字符串)
        redis_client.setex('ImageCaptcha:' + uuid, 60 * 5, text)
        print("tup",img_base64)
        # # 6.返回响应图片
        return HttpResponse(f'data: image/png;base64,{img_base64}')
